<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    var data = [{
        id: 1,
        name: '家电',
        goods: [{
            id: 11,
            gname: '冰箱',
            goods: [{
                id: 111,
                gname: '海尔'
            }, {
                id: 112,
                gname: '美的'
            },

            ]

        }, {
            id: 12,
            gname: '洗衣机'
        }]
    }, {
        id: 2,
        name: '服饰'
    }];

    // 递归获取ID的商品
    function getGoodsByID(dataList, id) {
        let o = {};
        dataList.forEach(el => {
            if (id == el.id) o = el;
            else if (el.goods && el.goods.length)
                o = getGoodsByID(el.goods, id)
        });
        return o;
    }

    console.log(getGoodsByID(data, 112));

    // 数据扁平化
    function plainGoods(dataList, newList) {
        newList = newList || [];
        dataList.forEach(el => {
            if (el.goods && el.goods.length) {
                plainGoods(el.goods, newList);
                delete el.goods;
            }
            newList.push(el);
        })
    }

    plainGoods(data, goods = []);
    console.log(goods);
</script>

</html>